<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="500px"
    :close-on-click-modal="false"
    append-to-body
  >
    <SubmitForm
      :rule-form="ruleForm"
      :rules="rules"
      :form-list="formList"
      @change="handleFormChange"
      @save="onSave"
      @close="dialogVisible = false"
    />
  </el-dialog>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'FormAdd',
  data() {
    return {
      apiKey: 'district',
      dialogVisible: false,
      dialogTitle: '',
      parentRow: null,
      ruleForm: {},
      defaultForm: {
        name: '',
        code: '',
        parent_id: null
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }]
      },
      formList: []
    }
  },
  methods: {
    updateFormList() {
      this.formList = [
        {
          label: '名称',
          prop: 'name',
          name: 'input',
          clearable: true,
          placeholder: '请输入名称'
        },
        {
          label: '编码',
          prop: 'code',
          name: 'input',
          clearable: true,
          placeholder: '请输入编码'
        }
      ]
    },
    handleFormChange({ key, val }) {
      this.ruleForm[key] = val
    },
    open(row = null, parentRow = null) {
      this.dialogVisible = true
      this.dialogTitle = row ? '编辑区域' : (parentRow ? '新增子级' : '新增区域')
      this.parentRow = parentRow
      this.ruleForm = row ? { ...row } : { ...this.defaultForm }
      if (parentRow) {
        this.ruleForm.parent_id = parentRow.id
      }
      this.updateFormList()
    },
    async onSave() {
      try {
        const data = { ...this.ruleForm }
        if (this.ruleForm.id) {
          await http[this.apiKey].update(this.ruleForm.id, data)
        } else {
          await http[this.apiKey].create(undefined,data)
        }
        this.$message.success('保存成功')
        this.dialogVisible = false
        this.$emit('get-page')
      } catch (error) {
        console.error(error)
      }
    }
  }
}
</script>
